<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Maze</title>
</head>
<body onload="build()">
<h2>Maze</h2>
<canvas id="canvas" width='400' height='200'>
Sorry: Browser does not support Graphics Canvas
</canvas>
<script type="text/javascript">


var NROW = 30 , NCOL=20 , L = 10;
var stack = new Array ();
var maze ;
var ctx ;
var px=0,py=0;

function init(){
	
	maze = new Array(NROW);
	for(j=0;j<NROW;j++){
		maze[j]=new Array(NCOL);
		for(i=0;i<NCOL;i++)
			maze[j][i]=30;
	}
	
	var canvas=document.getElementById("canvas");
	ctx=canvas.getContext("2d");
	px = Math.floor(Math.random()*NROW-1)+1;
	py = Math.floor(Math.random()*NCOL-1)+1;
	
	maze[px][py]=30;
	
}

function check(x,y,d){
	if(x<1 || x> NCOL-1) return false;
	if(y<1 || y> NROW-1) return false;
	if(maze[y][x]==0) return false;
	switch(d){
		case 2: // est 
			if(maze[y-1][x]==30 && maze[y+1][x]==30 && maze[y][x+1]==30 )
				return true;
		break;
		case 4: // sud 
			if(maze[y][x-1]==30 && maze[y][x+1]==30 && maze[y+1][x]==30 )
				return true;
		break;
		case 8: // west 
			if(maze[y-1][x]==30 && maze[y+1][x]==30 && maze[y][x-1]==30 )
				return true;
		break;
		case 16: // north 
			if(maze[y][x-1]==30 && maze[y][x+1]==30 && maze[y-1][x]==30 )
				return true;
		break;
	}
	return false;
}

function draw(){
	
	ctx.beginPath();  
	ctx.fillStyle="gray";
	ctx.fillRect(0,0,NROW*L,NCOL*L);
	ctx.fillStyle="yellow";
	for(j=0;j<NROW;j++){
		for(i=0;i<NCOL;i++){
			if(	maze[j][i]!=30){
				ctx.clearRect(i*L,j*L,L,L);
				if (maze[j][i]!=0)
					ctx.fillRect(i*L,j*L,L,L);
			}
		}
	}
	ctx.closePath();
}

function build(){
	init();
	do {
		c = maze[py][px];
		if(c==0){
			var obj = stack.pop();
			alert(obj);
			px = obj[0]; 
			py = obj[1];
			continue;
		}
		var d = Math.floor(Math.random()*3)+1;
		d = Math.pow(2,d);
		switch (d){
			case 2:
				maze[py][px] &= ~d ;
				if(check(px+1,py,d)){
					stack.push([px,py]);
					px +=1;
				}
			break;
			case 4:
				maze[py][px] &= ~d ;
				if(check(px,py-1,d)){
					stack.push([px,py]);
					py -=1;
				}
			break;
			case 8:
				maze[py][px] &= ~d ;
				if(check(px-1,py,d)){
					stack.push([px,py]);
					px -=1;
				}
			break;
			case 16:
				maze[py][px] &= ~d ;
				if(check(px,py+1,d)){
					stack.push([px,py]);
					py +=1;
				}
			break;
			default:
				alert("error:"+d);
				exit;
		}
		draw();
		//alert(stack.length);
	}while(stack.length!=0 &&  stack.length<400 );
}


</script>
</body>
</html>